# -*- coding: utf-8 -*-
"""
@Time ： 2021/3/18 23:47
@Auth ： 买菠萝凤梨
@File ：log.py
@IDE ：PyCharm
@Motto：work steadily

"""
import logging
import os
import time

class Log():

    def __init__(self):
        root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.logname = os.path.join(root_path,'report','log','{}.log'.format(time.strftime('%Y-%m-%d')))

    def __printconsole(self,level,message):
        #创建logger对象
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        #创建文件写入特定路径
        filepath = logging.FileHandler(self.logname,'a',encoding='utf-8')
        filepath.setLevel(logging.DEBUG)
        #将日志信息写入控制台
        consolelog = logging.StreamHandler()
        consolelog.setLevel(logging.DEBUG)
        #信息格式化
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s-')
        #将格式化写入日志
        filepath.setFormatter(formatter)
        consolelog.setFormatter(formatter)
        #将log日志写入logger对象里面
        logger.addHandler(filepath)
        logger.addHandler(consolelog)
        #判断日志等级
        if level == 'info':
            logger.info(message)
        elif level == 'debug':
            logger.debug(message)
        elif level == 'warning':
            logger.warning(message)
        elif level == 'error':
            logger.error(message)
        logger.removeHandler(filepath)
        logger.removeHandler(consolelog)
        # 关闭打开的文件
        filepath.close()

    def info(self,message):
        self.__printconsole('info',message)

    def debug(self,message):
        self.__printconsole('debug',message)

    def warning(self,message):
        self.__printconsole('warning',message)

    def error(self,message):
        self.__printconsole('error',message)



if __name__ == '__main__':
    Log().info('调试')
    Log().debug('测试')
    Log().warning('CS')
    Log().error('csa')

    def cs(message):
        print('{}通过'.format(message))
        Log().info('测试通过')

    cs('测试')










